package controller;

import dao.RaiderDao;
import model.Raider;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

public class RaiderController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession().getAttribute("users")==null){
            //用户没有登录，不能发表
            req.setAttribute("error","用户尚未登录，不能发表攻略");
            resp.sendRedirect(req.getContextPath()+"/index.jsp");
            return;
        }
        req.setCharacterEncoding("utf-8");
        //获取攻略信息
        String headline = req.getParameter("headline");
        String content = req.getParameter("content");
        System.out.println("***标题"+headline);
        System.out.println("****内容"+content);

        //获取系统时间
        Date publishTime=new Date(System.currentTimeMillis());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        System.out.println(df.format(publishTime));

        if (headline == null||headline.length()==0){
            req.setAttribute("error","标题不能为空");
            req.getRequestDispatcher("/editRaider.jsp").forward(req,resp);
            return;
        }
        if (headline == null||headline.length()==0){
            req.setAttribute("error","文本不能为空");
            req.getRequestDispatcher("/editRaider.jsp").forward(req,resp);
            return;
        }
        Raider raider = new Raider();
        raider.setHeadline(headline);
        raider.setContent(content);
        raider.setPublishTime(publishTime);
        RaiderDao raiderDao = new RaiderDao();
        String idraider = raiderDao.addRaider(raider);
        if (idraider.equals("exist")){
            req.setAttribute("error","已经发表");
            req.getRequestDispatcher("/editRaider.jsq").forward(req,resp);
            return;
        }
        raider.setIdraider(idraider);
        req.getSession().setAttribute("headline",raider.getHeadline());
        req.getSession().setAttribute("content",raider.getContent());
        resp.sendRedirect(req.getContextPath()+"/raiders.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
